package developer.算法.链表.两两下相交链表节点;

/**
 * @author zhangyongkang
 * @time 2025/3/20 16:32
 * @description 给你一个链表，
 * 两两交换其中相邻的节点，并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。
 * 输入：head = [1,2,3,4]
 * 输出：[2,1,4,3]
 * 示例 2：
 * <p>
 * 输入：head = []
 * 输出：[]
 * 示例 3：
 * <p>
 * 输入：head = [1]
 * 输出：[1]
 * <p>
 * 链表中节点的数目在范围 [0, 100] 内
 * 0 <= Node.val <= 100
 */
public class LiangLiangXiangJiaoLianBiaoJieDian {


    public static void main(String[] args) {
        LiangLiangXiangJiaoLianBiaoJieDian solution = new LiangLiangXiangJiaoLianBiaoJieDian();
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
        ListNode listNode = solution.swapPair(
                head
        );

        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static ListNode swapPair(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = head.next;
        ListNode next = newHead.next;
        newHead.next = head;
        head.next = swapPair(next);
        return newHead;
    }


    public ListNode swapPair3(ListNode node) {
        if (node == null || node.next == null) {//排除边界情况
            return node;
        }
        ListNode newHeader = node.next;//当前分组的头
        ListNode next = newHeader.next;//下一组的待交换的头

        newHeader.next = node;
        node.next = swapPair3(next);
        return newHeader;
    }


    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHeader = head.next;
        head.next = swapPairs(head.next);

        return newHeader;
    }

//    class MinCha {
//        public ListNode swapPairs(ListNode head) {
//            if (head == null || head.next == null) {
//                return head;
//            }
//            ListNode newHead = head.next;
//            head.next = swapPairs(newHead.next);
//            newHead.next = head;
//            return newHead;
//        }
//
//    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
